import { PERIOD_DATA } from '@/constants/global.const';
import { useDeepCompareEffect } from 'ahooks';
import { Modal } from 'antd';
import type { FC } from 'react';
import { useState } from 'react';
import ChoseBox from '../ChoseBox';
import styles from './index.less';

type TProps = {
  visible: boolean;
  onSubmit: TAnyFunction;
  onCancel: TAnyFunction;
  data: any;
};

const DatePickerModal: FC<TProps> = (props) => {
  const { visible, onSubmit, onCancel, data } = props;
  const [checkedArr, setCheckedArr] = useState<TPeriodItem[]>([]);

  const handleSubmit = () => {
    onSubmit && onSubmit(checkedArr);
  };

  const handleClick = (item: TPeriodItem) => {
    const retArr = [...checkedArr];
    const index: number = retArr.findIndex((o) => o.value == item.value);
    if (index > -1) {
      retArr.splice(index, 1);
    } else {
      retArr.push(item);
    }
    setCheckedArr(retArr);
  };

  const checkAll = () => {
    setCheckedArr(PERIOD_DATA);
  };

  useDeepCompareEffect(() => {
    setCheckedArr(data);
  }, [data]);

  return (
    <Modal title="选择餐段" open={visible} width={600} onCancel={onCancel} onOk={handleSubmit}>
      <div className={styles.choseContainer}>
        <div className={styles.choseWrap}>
          {PERIOD_DATA.map((obj) => (
            <span key={obj.value} onClick={() => handleClick(obj)}>
              <ChoseBox
                name={obj.name}
                checked={checkedArr.map((o) => o.value).includes(obj.value)}
              />
            </span>
          ))}
        </div>
        <span onClick={checkAll}>
          <ChoseBox name="全部" color="#3546d0" />
        </span>
      </div>
    </Modal>
  );
};

export default DatePickerModal;
